package com.nxn.core.utils;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;

import com.nxn.core.model.User;

public class SendMail {

	@Autowired
	private JavaMailSender mailSender;
	
	public boolean sendEmail(final User user) {
		
		MimeMessagePreparator preparator = new MimeMessagePreparator() {
			public void prepare(MimeMessage mimeMessage) throws Exception {
				MimeMessageHelper message = new MimeMessageHelper(mimeMessage,
						true, "UTF-8");
				message.setSubject("Hello您好(中国)那些年有限公司用户注册验证");
				message.setTo(user.getEmail());
				message.setFrom("那些年有限公司");
				
				Map model = new HashMap();
				model.put("user", user);
//				String text = VelocityEngineUtils.mergeTemplateIntoString(
//						velocityEngine, "registration-confirmation.vm", "UTF-8", model);
				
				String text = "-------------";
				message.setText(text, true);
			}
		};
		try {
			this.mailSender.send(preparator);
			return true;
		} catch (MailException e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public void send() {

		//注意SimpleMailMessage只能用来发送text格式的邮件
		SimpleMailMessage mail = new SimpleMailMessage();

		try {
			mail.setTo("zhangleizlpd@sina.com");// 接受者
			mail.setFrom("quick meal team");// 发送者,这里还可以另起Email别名，不用和xml里的username一致
			mail.setSubject("spring mail test!");// 主题
			mail.setText("springMail的简单发送测试");// 邮件内容
			
			mailSender.send(mail);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	public void sendHTML() {
		MimeMessage mailMessage = mailSender.createMimeMessage();
		
		try {
			// 设置utf-8或GBK编码，否则邮件会有乱码
			MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true, "utf-8");
			messageHelper.setTo("zhangleizlpd@sina.com");// 接受者
			messageHelper.setFrom("html email");// 发送者
			messageHelper.setSubject("测试邮件");// 主题
			
			// 邮件内容，注意加参数true，表示启用html格式
			messageHelper.setText(
							"<html><head></head><body><h1>hello!!chao.wang</h1></body></html>",
							true);
			
		   //附件内容  
		   messageHelper.addInline("a", new File("E:/xiezi.jpg"));  
		   messageHelper.addInline("b", new File("E:/logo.png"));   
		   File file=new File("E:/测试中文文件.rar");    
		   // 这里的方法调用和插入图片是不同的，使用MimeUtility.encodeWord()来解决附件名称的中文问题  
		   messageHelper.addAttachment(MimeUtility.encodeWord(file.getName()), file);   
		   mailSender.send(mailMessage);  

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}

